//
//  SingleViewController.m
//  FlyGift
//
//  Created by lanou3g on 15/7/15.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "SingleViewController.h"

@interface SingleViewController () <UICollectionViewDataSource,UICollectionViewDelegate,WaterflowLayoutDelegate>
@property(nonatomic,strong)NSMutableArray *singeProArray;
@property(nonatomic,strong)UICollectionView *collectionView;
@property(nonatomic,strong)NSTimer *timer;
// 拼接单品页面接口
@property(nonatomic,assign)int offset;

@end

@implementation SingleViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.navigationBar.translucent = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    // 1.创建布局对象 设置布局对象的代理
    WaterflowLayout *layout = [[WaterflowLayout alloc]init];
    layout.waterflowDelegate = self;
    layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    layout.columnCount = 2;
    layout.columnMargin = 10;
    layout.rowMargin = 10;
    
    // 2.创建集合视图对象 设置集合视图对象的代理
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64) collectionViewLayout:layout];
    self.collectionView.backgroundColor = [UIColor colorWithRed:0.871 green:0.958 blue:1.000 alpha:1.000];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.view addSubview:_collectionView];
    
    [self singleProductDownRefreshData];
    [self singleProductUpRefreshData];
    [self addToTopButton];
    
}

#pragma mark - 返回attrs的高度(自定义布局对象的代理方法) -
- (CGFloat)waterflowLayout:(WaterflowLayout *)waterflowLayout heightForWidth:(CGFloat)width atIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.item == 0) {
        return 40;
    }else
    {
        return width * 220 / 160;
    }
}




#pragma mark - 返回分区数 -
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

#pragma mark - 返回每个分区cell个数 -
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.singeProArray.count + 1;
}

#pragma mark - 返回集合视图的cell -
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    // 注册 (共有两个自定义cell,所以注册两次)
    [self.collectionView registerClass:[SingleProductCellOne class] forCellWithReuseIdentifier:@"SingleProductOne"];
    [self.collectionView registerClass:[SingleProductCellTwo class] forCellWithReuseIdentifier:@"SingleProductTwo"];
    // 创建cell
    if (indexPath.item == 0) {
        SingleProductCellOne *singleCellOne = [collectionView dequeueReusableCellWithReuseIdentifier:@"SingleProductOne" forIndexPath:indexPath];
        return singleCellOne;
    }else
    {
        SingleProductCellTwo *singleCellTw0 = [collectionView dequeueReusableCellWithReuseIdentifier:@"SingleProductTwo" forIndexPath:indexPath];
        [singleCellTw0.collectBtn addTarget:self action:@selector(collectBtn:) forControlEvents:UIControlEventTouchUpInside];
        SingleProductModel *model = self.singeProArray[indexPath.item - 1];
        [singleCellTw0 setItemValueWithModel:model];
        return singleCellTw0;
    }
}


#pragma mark - 点击cell上的收藏button触发方法 -
- (void)collectBtn:(UIButton *)sender
{
    // 找到点击button所在的cell
    SingleProductCellTwo *cell = (SingleProductCellTwo *)sender.superview.superview;
    // cell对应的indexPath
    NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
    SingleProductModel *model = self.singeProArray[indexPath.item - 1];
    int number = [cell.collectLabel.text intValue];
    if (!model.isClick) {
        // 改变button的背景图片 收藏数目
        [cell.collectBtn setBackgroundImage:[UIImage imageNamed:@"shoucang2"] forState:UIControlStateNormal];
        model.favorites_count = [NSNumber numberWithInt:number + 1];
        cell.collectLabel.text = model.favorites_count.stringValue;
    }else
    {
        [cell.collectBtn setBackgroundImage:[UIImage imageNamed:@"shoucang1"] forState:UIControlStateNormal];
        model.favorites_count = [NSNumber numberWithInt:number - 1];
        cell.collectLabel.text = model.favorites_count.stringValue;
    }
    model.isClick = !model.isClick;
}


#pragma mark - 懒加载 -
- (NSMutableArray *)singeProArray
{
    if (!_singeProArray) {
        _singeProArray = [NSMutableArray array];
    }
    return _singeProArray;
}

#pragma mark - 界面即将出现时添加计时器 -
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    // 添加计时器
    self.timer = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(timer:) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop]addTimer:_timer forMode:NSDefaultRunLoopMode];
    
    
}
// 页面自动刷新
- (void)timer:(NSTimer *)sender
{
    // 获取当前的时间
    NSDate *nowDate = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"HH:mm"];
    NSString *nowTime = [formatter stringFromDate:nowDate];
    // 找到标记更新时间的cell
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:0];
    SingleProductCellOne *cell = (SingleProductCellOne *)[self.collectionView cellForItemAtIndexPath:indexPath];
    
    //    NSLog(@"%@",nowTime);
    // 根据当前时间判断更新时间
    NSArray *timeArray = [nowTime componentsSeparatedByString:@":"];
    int number = [timeArray[0] intValue] * 60 + [timeArray[1] intValue];
    if (number > 480 && number < 840) {
        cell.timeLable.text = @"14:00";
    }else
    {
        cell.timeLable.text = @"8:00";
    }
    // 判断是否该自动刷新产品
    if ([nowTime isEqualToString:@"8:00"] || [nowTime isEqualToString:@"14:00"]) {
        [self singleProductDownRefreshData];
    }
}

#pragma mark - 下拉刷新 -
- (void)singleProductDownRefreshData
{
    __weak typeof(self) weakSelf = self;
    [self.collectionView addLegendHeaderWithRefreshingBlock:^{
        // 拼接接口
        weakSelf.offset = 0;
        NSString *url = [singleURL stringByAppendingFormat:@"%d",weakSelf.offset];
        NSMutableArray *arr = [NSMutableArray array];
        // 解析数据
        [LORequestManger GET:url success:^(id response) {
            weakSelf.collectionView.header.updatedTimeHidden = YES;
            NSDictionary *dic = (NSDictionary *)response;
            NSDictionary *dic2 = [dic valueForKey:@"data"];
            NSArray *array = [dic2 valueForKey:@"items"];
            for (NSDictionary *obj in array) {
                NSDictionary *dic3 = [obj valueForKey:@"data"];
                SingleProductModel *model = [SingleProductModel singleProductModelWithDictionary:dic3];
                [arr addObject:model];
                //            NSLog(@"产品的名称: %@",model.name);
            }
            // 清空原先的数据
            [weakSelf.singeProArray removeAllObjects];
            weakSelf.singeProArray = nil;
            // 加载当前解析出来的数据
            [weakSelf.singeProArray addObjectsFromArray:arr];
            [weakSelf.collectionView reloadData];
            [weakSelf.collectionView.header endRefreshing];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            nil;
        }];
    }];
    [self.collectionView.header beginRefreshing];
}


#pragma mark - 上拉刷新 -
- (void)singleProductUpRefreshData
{
    __weak typeof(self) weakSelf = self;
    [self.collectionView addLegendFooterWithRefreshingBlock:^{
        weakSelf.offset += 20;
        NSLog(@"%d",weakSelf.offset);
        NSString *url = [singleURL stringByAppendingFormat:@"%d",weakSelf.offset];
        [LORequestManger GET:url success:^(id response) {
            NSDictionary *dic = (NSDictionary *)response;
            NSDictionary *dic2 = [dic valueForKey:@"data"];
            NSArray *array = [dic2 valueForKey:@"items"];
            for (NSDictionary *obj in array) {
                NSDictionary *dic3 = [obj valueForKey:@"data"];
                SingleProductModel *model = [SingleProductModel singleProductModelWithDictionary:dic3];
                [weakSelf.singeProArray addObject:model];
                //            NSLog(@"产品的名称: %@",model.name);
            }
            [weakSelf.collectionView reloadData];
            [weakSelf.collectionView.footer endRefreshing];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            nil;
        }];
    }];
}


#pragma mark - 点击按钮回到顶部-
-(void)addToTopButton
{
    UIButton * toTopButton = [UIButton buttonWithType:UIButtonTypeSystem];
    toTopButton.frame = CGRectMake(kScreenWidth - kP6width(60), kScreenHeight - kP6Height(250), kP6width(40), kP6width(40));
    [toTopButton setBackgroundImage:[UIImage imageNamed:@"home_back_top@3x"] forState:UIControlStateNormal];
    [toTopButton addTarget:self action:@selector(toTop) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:toTopButton];
}
-(void)toTop
{
    [self.collectionView setContentOffset:CGPointMake(0, 0) animated:YES];
    NSLog(@"回到顶部");
}




@end
